package com.siteseat.crudeq.client;

import java.io.File;
import java.util.List;

import com.siteseat.common.misc.IOHelper;
import com.siteseat.common.misc.TimeHelper;

/**
 *
 */
public class ConsoleMain {

  private static void dump( ClientMessage m ) {
    String txt = new String(m.getPayload(), m.getContentLocalOffset(), m.getContentSize(),  IOHelper.CHARSET );
    String tmp = "commited=" + m.isCommited() 
              + "chunkId=" + m.getChunkId() 
              + ",payloadBase=" + m.getPayloadBase() 
              + ",queueId=" + m.getQueueId() 
              + ",payloadSize=" + m.getPayloadSize()
              + ",payloadLocalOffset=" + m.getPayloadLocalOffset()
              + ",receiveTimestamp=" + TimeHelper.format( m.getReceiveTimestamp() )
              + ",nextPayloadBase=" + m.getNextPayloadBase()
              + ": " + txt;
    System.out.println( tmp );
  }
  
  /**
   *
   *
   */
  public static void main( String args[] ) throws Exception {    
    ClientProfile profile = ClientProfile.load( new File( "c:\\crudeq_client_profile.json" ), true );    
    Client c = new Client( profile );
    c.start();
    
    List<ClientMessage> msgs = c.history( 1 );
    System.out.println( msgs.size() );
    for( ClientMessage m: msgs )  {      
      dump( m );
    }

    int count = 1;
    
    for( int i = 1; i <= count; i++ ) {
      c.click( 1, TimeHelper.formatCurrentTime() );
    }
    
    c.subscribe( Integer.valueOf(1) );
    c.startWaitMessage();
    
    c.click( 1, TimeHelper.formatCurrentTime() );
    
    int i = 0;
    while( i < 2 ) {
      msgs = c.waitNextMessage();
      if( msgs == null || msgs.size() == 0 ) {
        Thread.sleep( 800 );
        continue;
      }
      if( msgs == ClientMessage.STOPPED_LIST ) {
        break;
      }
      for( ClientMessage m: msgs ) {
        if( m == ClientMessage.STOPPED ) {
          break;
        }
        if( m != null ) {
          i++;
          dump( m );
        }
      }
    }
    
    c.shutdown();
  }

}